package cn.elead.chaos.sso.server.web.login.service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import cn.elead.chaos.sso.server.properties.SsoProperties;
import cn.hutool.core.util.ObjectUtil;

/**
 * 限制 key 只能为 String
 *
 * @param <String>
 * @param <V>
 */
@Service
@SuppressWarnings({ "hiding", "rawtypes", "unchecked" })
public class StringRedisService<String, V> {

	@Autowired
	private RedisTemplate redisTemplate;
	
	@Autowired
	private SsoProperties ssoProperties;

	// =====================================common start=====================================

	public Boolean expire(String key, long timeout, TimeUnit timeUnit) {
		// 设置过期时间
		return redisTemplate.expire(key, timeout, timeUnit);
	}

	public Boolean delete(String key) {
		return redisTemplate.delete(key);
	}
	
	public Long deleteBykeys(String keys) {
		return delete(redisTemplate.keys(keys));
	}
	
	public Long delete(Set<String> keys) {
		if(ObjectUtil.isEmpty(keys)) {
			return 0L;
		}
		return redisTemplate.delete(keys);
	}

	// =====================================common end=====================================

	// =====================================key value start=====================================

	public void set(String key, V value) {
		redisTemplate.opsForValue().set(key, value);
	}
	
	public void put(String key, V value) {
		if(ObjectUtil.isNotEmpty(ssoProperties) && ObjectUtil.isNotEmpty(ssoProperties.getAccessTokenMaxTimeToLiveInSeconds())) {
			set(key, value, ssoProperties.getAccessTokenMaxTimeToLiveInSeconds());
		}else {
			set(key, value, 14400);
		}
	}

	public void set(String key, V value, long timeout) {
		redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
	}

	public void set(String key, V value, long timeout, TimeUnit timeUnit) {
		redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
	}

	public V get(String key) {
		ValueOperations<String, V> valueOperations = redisTemplate.opsForValue();
		return valueOperations.get(key);
	}
	
	public Set<String> keys(String keys) {
		return redisTemplate.keys(keys);
	}

	// =====================================key value end=====================================

}
